{
 "cells": [
  {
   "cell_type": "raw",
   "id": "10238e62-3465-4973-9279-606cbb7ccf16",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "---\n",
    "sidebar_label: SerpAPI\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6f91f20",
   "metadata": {},
   "source": [
    "# SerpAPI\n",
    "\n",
    "[SerpAPI](https://serpapi.com/) allows you to integrate search engine results into your LLM apps\n",
    "\n",
    "This guide provides a quick overview for getting started with the SerpAPI [tool](/docs/integrations/tools/). For detailed documentation of all `SerpAPI` features and configurations head to the [API reference](https://api.js.langchain.com/classes/_langchain_community.tools_serpapi.SerpAPI.html).\n",
    "\n",
    "## Overview\n",
    "\n",
    "### Integration details\n",
    "\n",
    "| Class | Package | [PY support](https://python.langchain.com/docs/integrations/tools/serpapi/) | Package latest |\n",
    "| :--- | :--- | :---: | :---: |\n",
    "| [SerpAPI](https://api.js.langchain.com/classes/_langchain_community.tools_serpapi.SerpAPI.html) | [`@langchain/community`](https://www.npmjs.com/package/@langchain/community) | ✅ |  ![NPM - Version](https://img.shields.io/npm/v/@langchain/community?style=flat-square&label=%20&) |\n",
    "\n",
    "## Setup\n",
    "\n",
    "The integration lives in the `@langchain/community` package, which you can install as shown below:\n",
    "\n",
    "```{=mdx}\n",
    "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
    "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
    "\n",
    "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
    "\n",
    "<Npm2Yarn>\n",
    "  @langchain/community @langchain/core\n",
    "</Npm2Yarn>\n",
    "```\n",
    "\n",
    "### Credentials\n",
    "\n",
    "Set up an API key [here](https://serpapi.com/) and set it as an environment variable named `SERPAPI_API_KEY`.\n",
    "\n",
    "```typescript\n",
    "process.env.SERPAPI_API_KEY = \"YOUR_API_KEY\"\n",
    "```\n",
    "\n",
    "It's also helpful (but not needed) to set up [LangSmith](https://smith.langchain.com/) for best-in-class observability:\n",
    "\n",
    "```typescript\n",
    "process.env.LANGSMITH_TRACING=\"true\"\n",
    "process.env.LANGSMITH_API_KEY=\"your-api-key\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c97218f-f366-479d-8bf7-fe9f2f6df73f",
   "metadata": {},
   "source": [
    "## Instantiation\n",
    "\n",
    "You can import and instantiate an instance of the `SerpAPI` tool like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8b3ddfe9-ca79-494c-a7ab-1f56d9407a64",
   "metadata": {},
   "outputs": [],
   "source": [
    "import { SerpAPI } from \"@langchain/community/tools/serpapi\";\n",
    "\n",
    "const tool = new SerpAPI();"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74147a1a",
   "metadata": {},
   "source": [
    "## Invocation\n",
    "\n",
    "### [Invoke directly with args](/docs/concepts/#invoke-with-just-the-arguments)\n",
    "\n",
    "You can invoke the tool directly like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "65310a8b-eb0c-4d9e-a618-4f4abe2414fc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"type\":\"weather_result\",\"temperature\":\"63\",\"unit\":\"Fahrenheit\",\"precipitation\":\"3%\",\"humidity\":\"91%\",\"wind\":\"5 mph\",\"location\":\"San Francisco, CA\",\"date\":\"Sunday 9:00 AM\",\"weather\":\"Mostly cloudy\"}\n"
     ]
    }
   ],
   "source": [
    "await tool.invoke({\n",
    "  input: \"what is the current weather in SF?\"\n",
    "});"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6e73897",
   "metadata": {},
   "source": [
    "### [Invoke with ToolCall](/docs/concepts/#invoke-with-toolcall)\n",
    "\n",
    "We can also invoke the tool with a model-generated `ToolCall`, in which case a `ToolMessage` will be returned:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f90e33a7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ToolMessage {\n",
      "  \"content\": \"{\\\"type\\\":\\\"weather_result\\\",\\\"temperature\\\":\\\"63\\\",\\\"unit\\\":\\\"Fahrenheit\\\",\\\"precipitation\\\":\\\"3%\\\",\\\"humidity\\\":\\\"91%\\\",\\\"wind\\\":\\\"5 mph\\\",\\\"location\\\":\\\"San Francisco, CA\\\",\\\"date\\\":\\\"Sunday 9:00 AM\\\",\\\"weather\\\":\\\"Mostly cloudy\\\"}\",\n",
      "  \"name\": \"search\",\n",
      "  \"additional_kwargs\": {},\n",
      "  \"response_metadata\": {},\n",
      "  \"tool_call_id\": \"1\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "// This is usually generated by a model, but we'll create a tool call directly for demo purposes.\n",
    "const modelGeneratedToolCall = {\n",
    "  args: {\n",
    "    input: \"what is the current weather in SF?\"\n",
    "  },\n",
    "  id: \"1\",\n",
    "  name: tool.name,\n",
    "  type: \"tool_call\",\n",
    "}\n",
    "\n",
    "await tool.invoke(modelGeneratedToolCall)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "659f9fbd-6fcf-445f-aa8c-72d8e60154bd",
   "metadata": {},
   "source": [
    "## Chaining\n",
    "\n",
    "We can use our tool in a chain by first binding it to a [tool-calling model](/docs/how_to/tool_calling/) and then calling it:\n",
    "\n",
    "```{=mdx}\n",
    "import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
    "\n",
    "<ChatModelTabs customVarName=\"llm\" />\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "af3123ad-7a02-40e5-b58e-7d56e23e5830",
   "metadata": {},
   "outputs": [],
   "source": [
    "// @lc-docs-hide-cell\n",
    "\n",
    "import { ChatOpenAI } from \"@langchain/openai\"\n",
    "\n",
    "const llm = new ChatOpenAI({\n",
    "  model: \"gpt-4o-mini\",\n",
    "  temperature: 0,\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fdbf35b5-3aaf-4947-9ec6-48c21533fb95",
   "metadata": {},
   "outputs": [],
   "source": [
    "import { HumanMessage } from \"@langchain/core/messages\";\n",
    "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const prompt = ChatPromptTemplate.fromMessages(\n",
    "  [\n",
    "    [\"system\", \"You are a helpful assistant.\"],\n",
    "    [\"placeholder\", \"{messages}\"],\n",
    "  ]\n",
    ")\n",
    "\n",
    "const llmWithTools = llm.bindTools([tool]);\n",
    "\n",
    "const chain = prompt.pipe(llmWithTools);\n",
    "\n",
    "const toolChain = RunnableLambda.from(\n",
    "  async (userInput: string, config) => {\n",
    "    const humanMessage = new HumanMessage(userInput,);\n",
    "    const aiMsg = await chain.invoke({\n",
    "      messages: [new HumanMessage(userInput)],\n",
    "    }, config);\n",
    "    const toolMsgs = await tool.batch(aiMsg.tool_calls, config);\n",
    "    return chain.invoke({\n",
    "      messages: [humanMessage, aiMsg, ...toolMsgs],\n",
    "    }, config);\n",
    "  }\n",
    ");\n",
    "\n",
    "const toolChainResult = await toolChain.invoke(\"what is the current weather in sf?\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "9ac188a2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AIMessage {\n",
      "  \"tool_calls\": [],\n",
      "  \"content\": \"The current weather in San Francisco is mostly cloudy, with a temperature of 64°F. The humidity is at 90%, there is a 3% chance of precipitation, and the wind is blowing at 5 mph.\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "const { tool_calls, content } = toolChainResult;\n",
    "\n",
    "console.log(\"AIMessage\", JSON.stringify({\n",
    "  tool_calls,\n",
    "  content,\n",
    "}, null, 2));"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "573fb391",
   "metadata": {},
   "source": [
    "## Agents\n",
    "\n",
    "For guides on how to use LangChain tools in agents, see the [LangGraph.js](https://langchain-ai.github.io/langgraphjs/) docs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ac8146c",
   "metadata": {},
   "source": [
    "## API reference\n",
    "\n",
    "For detailed documentation of all `SerpAPI` features and configurations head to the API reference: https://api.js.langchain.com/classes/_langchain_community.tools_serpapi.SerpAPI.html"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "TypeScript",
   "language": "typescript",
   "name": "tslab"
  },
  "language_info": {
   "codemirror_mode": {
    "mode": "typescript",
    "name": "javascript",
    "typescript": true
   },
   "file_extension": ".ts",
   "mimetype": "text/typescript",
   "name": "typescript",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
